package com.banciyuan.bcywebview.utils.sys;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * <br/>
 * 系统工具类. <br/>
 * 主要用于获取系统信息,如设备ID、操作系统版本等
 * 需要别的功能请添加，一般不要直接修改
 *
 * @author hfxt2008
 */
public class SystemUtils {
    private static long DAY_SECONDS = 86400;

    public static String getSystemTime() {
        String dateString = Long.valueOf(System.currentTimeMillis() / 1000)
                + "";// 获取当前时间
        return dateString;
    }

    public static long getSystemTimeLongType() {
        return System.currentTimeMillis() / 1000;
    }

    public static boolean withinOneDay(long lastRecordTime) {
        return (getSystemTimeLongType() - lastRecordTime) < DAY_SECONDS;
    }

    /**
     * 获得今天的日期
     */
    public static String getDateYmd() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 获取android id
     *
     * @param context
     * @return
     */
    public static String getAndroidId(Context context) {
        if (isEmulator(context)) {
            return null;
        }
        try {
            return Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 是否是模拟器
     *
     * @param context
     * @return
     */
    public static boolean isEmulator(Context context) {
        String imei = getIMEI(context);
        if ("000000000000000".equals(imei)) {
            return true;
        }
        return (Build.MODEL.equalsIgnoreCase("sdk"))
                || (Build.MODEL.equalsIgnoreCase("google_sdk"))
                || Build.BRAND.equalsIgnoreCase("generic");
    }

    /**
     * 当前是否横屏
     *
     * @param context
     * @return
     */
    public static boolean isLandscape(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    }

    /**
     * 系统为Android3.0
     *
     * @return
     */
    public static boolean isHoneycomb() {
        // Can use static final constants like HONEYCOMB, declared in later
        // versions
        // of the OS since they are inlined at compile time. This is guaranteed
        // behavior.
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    /**
     * 系统为Android2.1.x
     *
     * @return
     */
    public static boolean isEclair_MR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1;
    }

    /**
     * 获取设备ID.
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        String id = getIMEI(context);
        if (TextUtils.isEmpty(id)) {
            id = getAndroidId(context);
        }
        return id;
    }

    /**
     * 获取手机IMEI.
     *
     * @param context
     * @return
     */
    private static String getIMEI(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            return imei;
        } catch (Exception ioe) {
        }
        return null;
    }

    /**
     * 获取设备名称.
     *
     * @return
     */
    public static String getBuildModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取设备SDK版本号.
     *
     * @return
     */
    public static int getBuildVersionSDK() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 获取设备系统版本号.
     *
     * @return
     */
    public static String getBuildVersionRelease() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 判断SD卡是否插入 即是否有SD卡
     */
    public static boolean isSDCardMounted() {
        return android.os.Environment.MEDIA_MOUNTED
                .equals(android.os.Environment.getExternalStorageState());
    }

    /**
     * 是否：已经挂载,但只拥有可读权限
     */
    public static boolean isSDCardMountedReadOnly() {
        return android.os.Environment.MEDIA_MOUNTED_READ_ONLY
                .equals(android.os.Environment.getExternalStorageState());
    }

    /**
     * 获取android当前可用内存大小
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);
        // mi.availMem; 当前系统的可用内存

        return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
    }

    /**
     * 获取屏幕的亮度
     */
    public static int getScreenBrightness(Activity activity) {
        int nowBrightnessValue = 0;
        ContentResolver resolver = activity.getContentResolver();
        try {
            nowBrightnessValue = android.provider.Settings.System.getInt(
                    resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }

    /**
     * 获取手机屏幕的宽和高
     *
     * @param c
     * @return map("w", width) map("h",height);
     */
    public static int getWidth(Context c) {
        DisplayMetrics metrics = c.getApplicationContext().getResources()
                .getDisplayMetrics();
        int width = metrics.widthPixels;
        return width;
    }

    /**
     * 获取手机屏幕的宽和高
     *
     * @param c
     * @return map("w", width) map("h",height);
     */
    public static HashMap<String, Integer> getWidth_Height(Context c) {
        DisplayMetrics metrics = c.getApplicationContext().getResources()
                .getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;

        HashMap<String, Integer> m = new HashMap<String, Integer>();
        m.put("w", width);
        m.put("h", height);
        return m;
    }

    /**
     * 获取手机屏幕的宽和高size wxh
     *
     * @param c
     * @return width X height
     */
    public static String getWidthXHeight(Context c) {
        Map<String, Integer> m = getWidth_Height(c);
        String size = m.get("w") + "x" + m.get("h");
        return size;
    }

    /**
     * 获取手机分辨率宽度大小
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources()
                .getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 获取手机分辨率长度大小
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources()
                .getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 4.0+获取虚拟导航高度
     *
     * @param context
     * @return
     */
    public int getNavigationBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            return resources.getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    /**
     * 获取手机状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Rect rect = new Rect();
        ((FragmentActivity) context).getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(rect);
        return rect.top;
    }

    /**
     * 获取应用窗口高度
     *
     * @param context
     * @return
     */
    public static int getAppWindowHeight(Context context) {
        Rect rect = new Rect();
        ((FragmentActivity) context).getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(rect);
        return rect.bottom - rect.top;
    }

    /**
     * 得到dimen定义的大小
     *
     * @param context
     * @param dimenId
     * @return
     */
    public static int getDimension(Context context, int dimenId) {
        return (int) context.getResources().getDimension(dimenId);
    }

    private static String VERSTION_FIRST_START_APP_KEY = "first_start_%s_app_key";
    private static String VERSTION_PREF = "VERSTION_PREF";

    /**
     * 是否第一次启动应用
     */
    public static boolean firstStartVersion(Context context) {
        return SPHelper.getBoolean(context, SPConstant.SPNAME_VERSTION_PREF,
                getVersionFirstStartKey(context), true);
    }

    /**
     * @param context
     * @return
     */
    public static void markFirstStartVersion(Context context) {
        clearVersionPrefKey(context);
        SPHelper.putBoolean(context, SPConstant.SPNAME_VERSTION_PREF,
                getVersionFirstStartKey(context), false);
    }

    /**
     * 清除不包含version的key值
     *
     * @param context
     */
    private static void clearVersionPrefKey(Context context) {
        SharedPreferences sp = SPHelper.getSharedPreferences(context,
                SPConstant.SPNAME_VERSTION_PREF);
        Map<String, ?> map = sp.getAll();
        if (null == map) {
            return;
        }
        Set<String> key = map.keySet();
        if (null == key) {
            return;
        }

        Iterator<String> it = key.iterator();
        Editor editor = null;
        String currentVersionKey = getVersionFirstStartKey(context);
        while (it.hasNext()) {
            String s = it.next();
            if (!TextUtils.isEmpty(s) && !s.equals(currentVersionKey)) {
                if (editor == null) {
                    editor = sp.edit();
                }
                editor.remove(s);
            }
        }
        if (editor != null) {
            editor.commit();
        }
    }

    private static String getVersionFirstStartKey(Context context) {
        String vnumber = context.getString(R.string.versionnum);
        return String.format(VERSTION_FIRST_START_APP_KEY, vnumber);
    }

    /**
     * 返回应用Name
     *
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        return getAppVersion(context, context.getPackageName());
    }

    /**
     * 返回应用版本号
     *
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        return getAppVersionCode(context, context.getPackageName());
    }

    /**
     * 根据packageName包名的应用获取应用版本名称,如未安装返回null
     *
     * @param context
     * @param packageName
     * @return
     */
    public static String getAppVersion(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return null;
        }
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    packageName, 0);
            return info.versionName;
        } catch (NameNotFoundException e) {
            return null;
        }
    }

    /**
     * 根据packageName包名的应用获取应用版本名称,如未安装返回null
     *
     * @param context
     * @param packageName
     * @return
     */
    public static int getAppVersionCode(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return 0;
        }
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    packageName, 0);
            return info.versionCode;
        } catch (NameNotFoundException e) {
            return 0;
        }
    }

    /**
     * 根据packageName包名的应用获取应用信息,如未安装返回null
     *
     * @param context
     * @param packageName
     * @return
     */
    public static PackageInfo getAppInfo(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return null;
        }
        try {
            return context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {
            return null;
        }
    }
}
